import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import hooks from "./hooks";

Vue.use(VueRouter);

// require.context()是webpack语法，创建自己的（模块）上下文。
// 三个参数：搜索文件夹目录，是否搜索子目录，匹配文件的正则表达式
const files = require.context("./", false, /\.router\.ts$/);
const routes: Array<RouteConfig> = [];

files.keys().forEach((key) => {
  routes.push(...files(key).default);
});

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

Object.values(hooks).forEach((hook) => {
  router.beforeEach(hook.bind(router)); // 将this绑定成router
});
// Object.values(hooks).forEach(hook=>{
//   router.beforeEach(hook.bind(router)); // 将this绑定成router
// });

export default router;
